package cn.tianyigps.tianyigpsaddress.customer;

import cn.tianyigps.tianyigpsaddress.assgin.AssginAddress;
import cn.tianyigps.tianyigpskafka.task.bean.Task;
import cn.tianyigps.tianyigpskafka.task.customer.Customer;
import cn.tianyigps.tianyigpspublic.util.FormatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * Created with IDEA
 *
 * @description: 中文地址解析消费者
 * @author: cui.guibin
 * @create: 2019/3/20 13:28
 **/
@Component
@Slf4j
public class AddressCustomer extends Customer {

    @Autowired
    private AssginAddress assginAddress;
    @Override
    public boolean checkTask(Task task) {

        Task nextTask = task.getNextTask();
        if (!Optional.ofNullable(nextTask).isPresent())
            return false;
        Map<String, Object> params = task.getParams();
        if (!Optional.ofNullable(params).isPresent())
            return false;
        String equipmentId = FormatUtil.format2String(params.get("equipmentId"));
        if (StringUtils.isEmpty(equipmentId))
            return false;
        Date start = FormatUtil.format2Date(params.get("start"));
        if (!Optional.ofNullable(start).isPresent())
            return false;
        Date end = FormatUtil.format2Date(params.get("end"));
        if (!Optional.ofNullable(end).isPresent())
            return false;

        String filter = FormatUtil.format2String(params.get("filter"));
        if (StringUtils.isEmpty(filter)){
            params.put("filter","all");
        }

        String mapType = FormatUtil.format2String(params.get("mapType"));
        if (StringUtils.isEmpty(mapType)){
            params.put("mapType","bd09");
        }
        Map<String, Object> sonParams = nextTask.getParams();
        if (!Optional.ofNullable(sonParams).isPresent())
            return false;
        String callback = FormatUtil.format2String(sonParams.get("callback"));
        if (StringUtils.isEmpty(callback))
          return false;
        return true;
    }

    @Override
    public void consume(Task task) {
        Map<String, Object> params = task.getParams();
        String equipmentId = (String) params.get("equipmentId");
        Date start = FormatUtil.format2Date(params.get("start"));
        Date end = FormatUtil.format2Date(params.get("end"));

        String filter = (String) params.get("filter");
        String mapType = (String) params.get("mapType");
        assginAddress.dealTask(equipmentId,start,end,filter,mapType,task);
    }
}
